package com.ea.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ea.admin.mapper.AdminAccountMapper;
import com.ea.admin.pojo.po.AdminAccount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class UserDetailsServiceImpl implements org.springframework.security.core.userdetails.UserDetailsService {
    //用户名映射到Nowuser对象的key前缀
    @Resource
    private AdminAccountMapper adminAccountMapper;

    /**
     * 前端需要调用ip:port/oauth/token（Post方法，表单形式）
     * 表单填入参数grant_type、client_id、client_secret、account、password
     *
     * @param username 用户名
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取用户账号信息
        LambdaQueryWrapper<AdminAccount> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdminAccount::getUsername, username);
        AdminAccount adminAccount = adminAccountMapper.selectOne(wrapper);

        // 判断用户是否存在
        if (adminAccount == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        //返回一个oauth2用户
        return new User(adminAccount.getUsername(), adminAccount.getPassword(), AuthorityUtils.createAuthorityList(adminAccount.getRole()));
    }
}
